#!/usr/bin/env python
# This program uses an external program or module to talk to the 2300
# and then stores the data in one or more data sinks.

import config

def store_mysql(config, data):
	"""
	Stores in a mysql database table in the format required for mysql2300
	"""
	import MySQLdb
	conn = MySQLdb.connect(host=config['host'], user=config['username'], passwd=config['password'], db=config['database'])
	cur = conn.cursor()
	cur.execute("INSERT INTO %s VALUES (NOW(),  %s, %s, %s, %s, %s, %s, %s, '%s', %s, %s, %s, %.1f, %s, '%s', '%s') "%(config['table'], data['Ti'], data['To'], data['DP'], data['RHi'], data['RHo'], data['WS'], data['DIR0'], data['DIRtext'], data['WC'], data['R1h'], data['R24h'], float(data['Rtot']), data['RP'], data['Tendency'], data['Forecast']))
	cur.close()
	conn.close()
	return

def store_drupal(config, data):
	"""
	Writes to an openweather XMLRPC sink
	"""
	import xmlrpclib
	import time
	s = xmlrpclib.ServerProxy(config['url'])
	package = {
		"timestamp":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['time'])),
		'temp':data['To'],
		'rel_hum':data['RHo'],
		'windspeed':data['WS'],
		'wind_angle':data['DIR0'],
		'wind_chill':data['WC'],
		'rain_1h':data['R1h'],
		'rain_total':data['Rtot'],
		'dewpoint':data['DP'],
		'rel_pressure':data['RP'],
		}
	if not s.openweather.addEntry(config['station_id'], config['username'], config['password'], package):
		print "Error talking to drupal at "+config['url']
	return

def store_console(config, data):
	"""
	Simply dumps to the console
	"""
	print data

def store_metakit(config, data):
	"""
	Store in a metakit file
	"""
	import metakit
	db = metakit.storage(config['file'], 1)
	w = db.getas("weather[timestamp:L,Ti:F,To:F,RHi:F,RHo:F,WS:F,DIR0:F,DP:F,WC:F,R1h:F,RP:F,Rtot:F]")
	data['timestamp'] = int(data['time'])
	data['Ti'] = float(data['Ti'])
	data['To'] = float(data['To'])
	data['RHi'] = float(data['RHi'])
	data['RHo'] = float(data['RHo'])
	data['WS'] = float(data['WS'])
	data['DIR0'] = float(data['DIR0'])
	data['DP'] = float(data['DP'])
	data['WC'] = float(data['WC'])
	data['R1h'] = float(data['R1h'])
	data['RP'] = float(data['RP'])
	data['Rtot'] = float(data['Rtot'])
	w.append(data)
	db.commit()


def toMPH(d):
	"""
	From kmh to mph
	"""
	return float(d)/ 1.609
def toInches(d):
	"""
	From mm to inches
	"""
	return float(d)/25.4
def toFarenheit(d):
	"""
	From deg C to deg F
	"""
	return (float(d)*1.8)+32
def toInhg(d):
	return float(d)*0.0295300
def store_wu(config, data):
	wu_url = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php"
	dateutc = time.strftime("%Y-%m-%d+%H:%M:%S",time.gmtime( data['time'] ))
	url = "%s?ID=%s&PASSWORD=%s&dateutc=%s&tempf=%s&dewptf=%s&humidity=%s&windspeedmph=%.2f&winddir=%.1f&rainin=%s&dailyrainin=%s&baromin=%.4f"%(wu_url, config['id'], config['password'],dateutc, toFarenheit(data['To']), toFarenheit(data['DP']), data['RHo'], toMPH(data['WS']), float(data['DIR0']), toInches(data['R1h']), toInches(data['R24h']), toInhg(data['RP']) )
	import urllib2
	f = urllib2.urlopen(url)
	#print f.readline()
	f.close()

try:
	f=open(config.Timestamp,'r')
	oldTimes_ = f.readlines()
	f.close()
	times = {}
	for t in oldTimes_:
		x = t.split(" ")
		times[x[0]] = int(x[1])
except:
	import traceback
	traceback.print_exc()
	times = {}

# Get data
import popen2
p = popen2.Popen3(config.Fetch2300)
p.wait() # wait for the program to exit

import time
newTime = int(time.time())

data = {}
data['time'] = newTime
for r in p.fromchild.readlines():
	r_ = r.split(" ")
	data[r_[0]] = r_[1].strip()

# Test we got all the data

for c in config.Sinks:
	if not times.has_key(c['name']) or not c.has_key("min_interval") or (times[c['name']] + 60*int(c['min_interval'])) < newTime :
		try:
			if c['type'] == 'mysql':
				store_mysql(c, data)
			elif c['type'] == 'drupal':
				store_drupal(c, data)
			elif c['type'] == 'console':
				store_console(c, data)
			elif c['type'] == 'wu':
				store_wu(c, data)
			elif c['type'] == 'metakit':
				store_metakit(c, data)
			times[c['name']] = newTime
		except:
			print "Error writing to %s"%c['name']

f = open(config.Timestamp, 'w')
for t in times:
	f.write("%s %d\n"%(t, times[t]))
f.close()
